package com.example.sftpclient

import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.SFTPClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.security.Security

class SftpClient {
    private var ssh: SSHClient? = null
    private var sftp: SFTPClient? = null

    init {
        // 添加BouncyCastle作为安全提供程序
        Security.removeProvider("BC")  // 先移除已存在的BC提供程序（如果有）
        Security.addProvider(BouncyCastleProvider())
    }

    fun connect(host: String, username: String, password: String, port: Int = 22) {
        ssh = SSHClient()
        ssh?.addHostKeyVerifier(PromiscuousVerifier())
        ssh?.connect(host, port)
        ssh?.authPassword(username, password)
        sftp = ssh?.newSFTPClient()
    }

    fun uploadFile(localPath: String, remotePath: String) {
        sftp?.put(localPath, remotePath)
    }

    fun downloadFile(remotePath: String, localPath: String) {
        sftp?.get(remotePath, localPath)
    }

    fun listFiles(remotePath: String): List<RemoteFile> {
        return sftp?.ls(remotePath)?.map { entry ->
            RemoteFile(
                name = entry.name,
                path = remotePath + "/" + entry.name,
                isDirectory = entry.isDirectory,
                size = entry.attributes.size,
                modifyTime = entry.attributes.mtime * 1000L // 转换为毫秒
            )
        } ?: emptyList()
    }

    fun createDirectory(remotePath: String) {
        sftp?.mkdir(remotePath)
    }

    fun deleteFile(remotePath: String) {
        sftp?.rm(remotePath)
    }

    fun deleteDirectory(remotePath: String) {
        sftp?.rmdir(remotePath)
    }

    fun disconnect() {
        sftp?.close()
        ssh?.disconnect()
    }
}

data class RemoteFile(
    val name: String,
    val path: String,
    val isDirectory: Boolean,
    val size: Long,
    val modifyTime: Long
) 